package com.simplecontact.providers;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.simplecontact.classes.ContactDb;
import com.simplecontact.classes.Groups;
import com.simplecontact.databases.ContactDbOpenHelper;

public class GroupProvider extends ContentProvider {

	private ContactDbOpenHelper dbsur;
	private static final UriMatcher sUriMatcher;
	private static HashMap<String, String> sDicProjectionMap;
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = dbsur.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case 1:
            count = db.delete(Groups.GROUP_TABLE_NAME, where, whereArgs);
            break;

        case 2:
            String surId = uri.getPathSegments().get(1);
            count = db.delete(Groups.GROUP_TABLE_NAME, Groups.GroupColumns._ID + "=" + surId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
        case 1:        
            return Groups.GroupColumns.CONTENT_TYPE;
        case 2:
            return Groups.GroupColumns.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		if (sUriMatcher.match(uri) != 1) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }       

        if (values.containsKey(Groups.GroupColumns.GROUPNAME) == false) {            
            values.put(Groups.GroupColumns.GROUPNAME, "");
        }       
        
        SQLiteDatabase db = dbsur.getWritableDatabase();
        long rowId = db.insert(Groups.GROUP_TABLE_NAME, Groups.GroupColumns._ID, values);
        if (rowId > 0) {
            Uri surUri = ContentUris.withAppendedId(Groups.GroupColumns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(surUri, null);
            return surUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		dbsur = new ContactDbOpenHelper(getContext(), ContactDb.CONTACT_DATABASE_NAME, null, ContactDb.DATABASE_VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(Groups.GROUP_TABLE_NAME);

        switch (sUriMatcher.match(uri)) {
        case 1:
            qb.setProjectionMap(sDicProjectionMap);
            break;
        case 2:
            qb.setProjectionMap(sDicProjectionMap);
            qb.appendWhere(Groups.GroupColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = Groups.GroupColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = dbsur.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		SQLiteDatabase db = dbsur.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case 1:
            count = db.update(Groups.GROUP_TABLE_NAME, values, where, whereArgs);
            break;
        case 2:
            String surId = uri.getPathSegments().get(1);
            count = db.update(Groups.GROUP_TABLE_NAME, values, Groups.GroupColumns._ID + "=" + surId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Groups.AUTHORITY, "groups", 1);
        sUriMatcher.addURI(Groups.AUTHORITY, "groups/#", 2);        

        sDicProjectionMap = new HashMap<String, String>();
        sDicProjectionMap.put(Groups.GroupColumns._ID, Groups.GroupColumns._ID);        
        sDicProjectionMap.put(Groups.GroupColumns.GROUPNAME, Groups.GroupColumns.GROUPNAME);        
    }
}
